<template>
	<a-modal :visible="props.visible" width="90vw" centered destroyOnClose @ok="handleOk" @cancel="cancel" :maskClosable="false">
		<template #title>
			<span>编辑加收费用</span>
			<a-button class="ml20" size="small" type="primary" @click="onClickToAddTogether">添加</a-button>
		</template>
		<template #footer>
			<a-button @click="cancel">退出</a-button>
			<a-button @click="handleAddAll" type="primary">添加至所有房源</a-button>
			<a-button @click="handleOk" type="primary">仅添加至本房间</a-button>
		</template>
		<vxe-table ref="otherBillTable" :data="tableData" v-bind="otherBillTableOption">
			<vxe-column min-width="150px" align="center" class-name="fee-subject-change">
				<template #header>
					<span v-color="{color: 'danger'}">*</span>
					费用科目
				</template>
				<template #default="{row, rowIndex}">
					<a-select
						v-model:value="row.feeSubjectId"
						:disabled="row.disabled"
						:bordered="false"
						:options="options.feeSubjects"
						@change="(value: string) => feeSubjectChange(value, row)"
						show-search
						option-filter-prop="name"
						:field-names="{label: 'name', value: 'id', options: 'metaList'}"
						placeholder="请选择费用科目" />
				</template>
			</vxe-column>
			<vxe-column min-width="150px" align="center" class-name="fee-subject-change">
				<template #header>
					<span v-color="{color: 'danger'}">*</span>
					付款方式
				</template>
				<template #default="{row, rowIndex}">
					<a-select
						v-model:value="row.periodMonth"
						:disabled="row.disabled"
						:bordered="false"
						:options="periodMonthOptions"
						placeholder="请选择付款方式" />
				</template>
			</vxe-column>
			<vxe-column min-width="150px" align="center">
				<template #header>
					<span v-color="{color: 'danger'}">*</span>
					金额
				</template>
				<template #default="{row, rowIndex}">
					<a-input-number
						v-model:value="row.price"
						:bordered="false"
						:controls="false"
						:min="0"
						:precision="2"
						placeholder="请输入金额" />
				</template>
			</vxe-column>
			<vxe-column title="操作" width="60px" align="center">
				<template #default="{row, rowIndex}">
					<a v-color="{color: 'danger'}" @click="onClickToRemoveRow(rowIndex, otherBillTable)">
						<svg-icon icon-class="trash" />
					</a>
				</template>
			</vxe-column>
		</vxe-table>
		<span v-show="validate" v-color="{color: 'danger'}">{{ validate }}</span>
	</a-modal>

</template>
<script lang="ts" setup>
	import {VxeTableInstance, VxeTableProps} from 'vxe-table'
	import {Modal, message} from 'ant-design-vue'
	import {CERTIFICATION_TYPE_MAP} from 'yuxin-base/src/constant/index'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import {DIC_LABEL_MAP} from 'yuxin-base/src/constant'
	import {onMounted, reactive, ref, watch, createVNode} from 'vue'
	import XEUtils from 'xe-utils'
	import {periodMonthOptions} from '@/utils'
	const emit = defineEmits(['update:visible', 'addAll', 'update:data', 'success'])
	const otherBillTable = ref<VxeTableInstance>()
	const otherBillTableOption = reactive<VxeTableProps>({
		size: 'mini',
		maxHeight: 200,
		border: true,
		cellStyle: {padding: 0},
		rowClassName: 'edit-table-row'
	})

	const props = withDefaults(
		defineProps<{
			visible: boolean
			data?: any
		}>(),
		{
			visible: false,
			data: {}
		}
	)

	const tableData: any = ref([])

	const options = reactive<any>({
		// 费用科目
		feeSubjects: [],
		// 证件类型
		certificateTypes: Object.keys(CERTIFICATION_TYPE_MAP).map(key => ({
			label: CERTIFICATION_TYPE_MAP[key],
			value: Number(key)
		}))
	})
	watch(
		() => props.visible,
		val => {
			if (val) {
				tableData.value = XEUtils.clone(props.data, true)
				otherBillTable.value?.reloadData(tableData.value)
			}
		}
	)
	onMounted(() => {
		getDics()
	})
	// 获取字典
	const getDics = () => {
		settingApi.getDicListByLabel(DIC_LABEL_MAP['FEESUBJECT']).then(({data}) => (options.feeSubjects = data))
	}
	// 添加同住人
	const onClickToAddTogether = () => {
		tableData.value.push({})

		otherBillTable.value?.reloadData(tableData.value)
	}
	/** 换房手续费 转租手续费 */
	const targetFeeTagList = ['EXCHANGE_PROCEDURE_FEE', 'SUBLEASE_PROCEDURE_FEE']
	/** 加收费用 费用科目 change事件 */
	const feeSubjectChange = (value: string, row: any) => {
		let target: any = {}
		let tag = ''
		options.feeSubjects.forEach(item => {
			const obj = item.metaList.find(v => v.id === value)
			if (obj) {
				target = item
				tag = obj.tag
			}
		})
		if (target.label === 'FEESUBJECT@DEPOSIT') {
			// 付款方式 为 一次性付清 且 不可以修改
			row.periodMonth = 99
			row.disabled = true
		} else if (target.label === 'FEESUBJECT@PROCEDURE' && targetFeeTagList.includes(tag)) {
			// 手续大类  && entity.signType === 4
			row.periodMonth = 99
			row.disabled = true
		} else {
			row.disabled = false
			if (row.periodMonth === 99) {
				delete row.periodMonth
			}
		}
	}
	const validate = ref('')
	const validateFn = () => {
		const field = ['feeSubjectId', 'periodMonth', 'price']
		let validateRes = true
		tableData.value.forEach(e => {
			const valueList = Object.values(XEUtils.pick(e, field))
			validateRes = valueList.filter(e=>e).length === valueList.length && field.length === valueList.length
		})
		if (!validateRes) {
			validate.value = '请完善加收费用信息'
		} else {
			validate.value = ''
		}
		return validateRes
	}
	const cancel = () => {
		tableData.value = []
		otherBillTable.value?.reloadData(tableData.value)
		emit('update:visible', false)
	}
	const handleOk = () => {
		if (!validateFn()) {
			return
		}
		emit(
			'update:data',
			tableData.value.map(e => XEUtils.omit(e, ['_X_ROW_KEY']))
		)
		emit(
			'success',
			tableData.value.map(e => XEUtils.omit(e, ['_X_ROW_KEY']))
		)

		cancel()
	}
	const handleAddAll = () => {
		if (!validateFn()) {
			return
		}
		emit(
			'addAll',
			tableData.value.map(e => XEUtils.omit(e, ['_X_ROW_KEY']))
		)
		cancel()
	}
	const onClickToRemoveRow = (index: any, tableInstance: VxeTableInstance) => {
		Modal.confirm({
			title: '系统提示',
			content: '删除后无法恢复，确定删除？',
			centered: true,
			onOk() {
				tableInstance.data?.splice(index, 1)
				tableInstance.reloadData(tableInstance.data as [])
			}
		})
	}
</script>
<style lang="less" scoped>
	.ml20 {
		margin-left: 20px;
	}
</style>
